<template>
  <el-container>
    <el-aside style="padding:0; width:1042px; border:none">
      <el-table
        class="homeTable"
        :data="homeworkData"
        height="250"
        border
        :header-cell-style="{
          background: '#94AFCC',
          color: '#333333',
          padding: '0',
          height: '40px',
          fontSize: '14px',
          textAlign: 'center',
          fontWeight: '600',
        }"
        :row-style="{ height: '20px', padding: '0px' }"
        :cell-style="{
          padding: '0',
          textAlign: 'center',
          fontSize: '13px',
          color: '#333333',
        }"
      >
        <el-table-column
          prop="homeworkTitle"
          label="课程作业名称"
          :resizable="false"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="homeworkContent"
          label="作业要求"
          :resizable="false"
          width="300"
        ></el-table-column>
        <el-table-column
          prop="publishTime"
          label="发布日期"
          :resizable="false"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="deadline"
          label="截止日期"
          :resizable="false"
          width="180"
        ></el-table-column>
        <el-table-column label="提交信息" :resizable="false" width="100">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="lookSubmitInfo(scope.row)"
              class="tableBtn"
              >查看</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="majorName"
          label="统计信息"
          :resizable="false"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="lookStatisticsInfo(scope.row)"
              class="tableBtn"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-aside>
    <el-main style="padding:0;text-align:center;">
      <el-button
        style="margin-top:50px; width:150px; background-color:#5988B3; color:#F2F2F2"
        @click="dialogVisible = true"
        >发布课程作业</el-button
      >
      <el-button
        style="margin-top:30px; width:150px;background-color:#5988B3; color:#F2F2F2"
        @click="studentStatistics"
        disabled
        >学生作业情况统计</el-button
      >
    </el-main>
    <el-dialog
      title="发布课程作业"
      :visible.sync="dialogVisible"
      width="1000px"
      :before-close="handleClose"
      :close-on-click-modal="false"
      center
    >
      <el-main class="publishTable" style="padding:10px 40px">
        <el-form label-width="120px">
          <el-row>
            <el-col :span="13">
              <el-form-item label="课程作业名称">
                <el-input
                  placeholder="请输入作业标题"
                  v-model="publishHomework.homeworkTitle"
                />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="截止日期">
                <el-date-picker
                  v-model="publishHomework.deadline"
                  type="datetime"
                  placeholder="选择截止日期"
                  format="yyyy-MM-dd HH:mm:ss"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="作业要求">
                <el-input
                  type="textarea"
                  placeholder="请输入作业具体内容"
                  v-model="publishHomework.homeworkContent"
                  resize="none"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider></el-divider>
        <el-form label-width="120px">
          <el-form-item label="相关附件">
            <div>
              <el-row>
                <el-col :span="24">
                  <!-- 选择上传文件 -->
                  <input id="fileSelector" type="file" name="filename" />
                </el-col>
                <el-col :span="24">
                  <div class="fileExplain">
                    只能上传单个.rar .zip .doc .docx .pdf
                    .jpg格式文件，文件不能超过500mb
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-form>
        <div style="text-align:center;margin-top:20px">
          <el-button class="publishBtn" @click="upLoad">发布课程作业</el-button>
        </div>
      </el-main>
      <div v-if="submiting">
        <div>文件上传进度</div>
        <el-progress :percentage="progress"></el-progress>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import COS from "cos-js-sdk-v5";
import $ from "jquery";

export default {
  data() {
    return {
      // 用来标识一节课
      identifier: "1",
      homeworkData: [
        // {
        //   hoemworkId: "1",
        //   homeworkTitle: "第十章作业",
        //   homeworkContent: "填空题：第3题",
        //   publishTime: "2020-11-12 22:41:52",
        //   deadline: "2020-12-11 21:36:00",
        // },
        // {
        //   hoemworkId: "2",
        //   homeworkTitle: "第十章作业",
        //   homeworkContent: "填空题：第3题",
        //   publishTime: "2020-11-12 22:41:52",
        //   deadline: "2020-12-11 21:36:00",
        // },
      ],
      dialogVisible: false,

      // 发送给后端的内容，详细见接口文档“发布作业”
      publishHomework: {
        homeworkTitle: "",
        homeworkContent: "",
        deadline: "",
        attachmentList: [
          {
            attachmentTitle: "",
            link: "",
          },
        ],
      },

      uploadFile: "",

      // 是否完成发布作业
      havePublished: false,
      // 上传进度
      progress: 0,
      // 是否正在上传
      submiting: false,
    };
  },
  methods: {
    //加载作业列表
    loadHomeworkList() {
      let options = this.$store.state.temp_courseSections[0];
      // let options = {
      //   periodId: 1,
      //   year: "2019",
      //   term: "上学期",
      //   courseId: 2,
      //   buildingId: "A1",
      //   roomNumber: "103",
      // };
      this.$http
        .post(this.$api.HomeWorkqueryWorkListOfT, options)
        .then((resp) => {
          if (resp.success) {
            // console.log(resp.data);
            this.homeworkData = resp.data;
          } else {
            this.$handleFailResp(this, resp);
          }
        });
    },

    // 查看提交信息
    lookSubmitInfo(item) {
      // 获取表格内的信息
      // console.log(item);
      /* 这里需要接口啦 */
      // 详细见接口文档“查询单个作业信息（教师）”
      // 路由
      this.$router.push({
        path: "/teacher/courseMangement/submitStatus",
        query: { homeworkId: item.homeworkId },
      });
    },

    // 查看统计信息
    lookStatisticsInfo(item) {
      /* 这里需要接口啦 */
      // 详细见接口文档“统计学生作业情况”
      console.log(item);
      this.$router.push({
        path: "/teacher/courseMangement/homeworkStatistics",
        query: { homeworkId: item.homeworkId },
      });
    },

    // 选择附件
    select() {
      // 获取上传文件的信息
      console.log(document.getElementById("fileSelector").files[0] == null);
      if (document.getElementById("fileSelector").files[0] != null) {
        this.uploadFile = document.getElementById("fileSelector").files[0];
        this.publishHomework.attachmentList[0].attachmentTitle = this.uploadFile.name;
      }
    },

    // 是否取消上传
    handleClose(done) {
      if (this.havePublished == false) {
        this.$confirm("取消发布作业？")
          .then((_) => {
            this.reset();
            done();
          })
          .catch((_) => {});
      } else {
        this.reset();
        done();
      }
    },

    // 重置状态
    reset() {
      console.log("我被重置啦");
      this.submiting = false;
      this.publishHomework.homeworkTitle = "";
      this.publishHomework.homeworkContent = "";
      this.publishHomework.deadline = "";
      this.publishHomework.attachmentList = [];
      // this.publishHomework.attachmentList[0].link = "";
      this.havePublished = false;
      // 清空input里面的文件
      console.log("reset");
      var obj = document.getElementById("fileSelector");
      obj.outerHTML = obj.outerHTML;
    },
    //发布作业
    submitHomework() {
      // 格式化时间
      Date.prototype.Format = function(fmt) {
        //author: meizz
        var o = {
          "M+": this.getMonth() + 1, //月份
          "d+": this.getDate(), //日
          "h+": this.getHours(), //小时
          "m+": this.getMinutes(), //分
          "s+": this.getSeconds(), //秒
          "q+": Math.floor((this.getMonth() + 3) / 3), //季度
          S: this.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            );
        return fmt;
      };
      if (
        this.publishHomework.deadline == "" ||
        this.publishHomework.homeworkTitle == ""
      ) {
        this.$myMessage.warning(this, "作业标题或截止日期不能为空");
        return;
      }
      let date = this.publishHomework.deadline.Format("yyyy-MM-dd  hh:mm:ss");
      let section = this.$store.state.temp_courseSections[0];
      // let section = {
      //   periodId: 1,
      //   year: "2019",
      //   term: "上学期",
      //   courseId: 2,
      //   buildingId: "A1",
      //   roomNumber: "103",
      // };
      let options = {
        periodId: section.periodId,
        year: section.year,
        term: section.term,
        courseId: section.courseId,
        buildingId: section.buildingId,
        roomNumber: section.roomNumber,
        homeworkTitle: this.publishHomework.homeworkTitle,
        homeworkContent: this.publishHomework.homeworkContent,
        deadline: date,
        attachmentList: this.publishHomework.attachmentList,
      };

      // return;
      // let options = {
      //   periodId: 1,
      //   year: "2019",
      //   term: "上学期",
      //   courseId: 2,
      //   buildingId: "A1",
      //   roomNumber: "103",
      //   homeworkTitle: "第123章作业",
      //   homeworkContent: "填空题：第3题",
      //   deadline: "2020-12-11  15:06:30",
      //   attachmentList: [],
      // };
      console.log("参数");
      console.log(options);
      this.$http.post(this.$api.HomeworkPublish, options).then((resp) => {
        if (resp.success) {
          this.$myMessage.success(this, "作业发布成功");
        } else {
          this.$handleFailResp(this, resp);
        }
      });
    },

    upLoad() {
      // 调用select函数获取文件信息
      this.select();
      // console.log("uploadFile");
      // console.log(this.uploadFile);
      // console.log(this.uploadFile == "");
      var _this = this;

      // 弹出提示框询问是否确认提交
      this.$confirm("确认发布作业吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("正在发布");
          // console.log(this.uploadFile == "")
          if (_this.uploadFile == "") {
            // 没有附件，向后端发请求，详细见接口文档“发布作业”
            _this.submitHomework();
            _this.havePublished = true;
            _this.$router.go(0);
          } else {
            console.log("上传文件");

            // 身份认证
            var cos = this.getCOS();
            _this.submiting = true;
            cos.putObject(
              {
                Bucket: "mybucket-1304114494",
                Region: "ap-guangzhou",
                // 唯一标识文件的key：前面为文件夹，后面为文件名
                Key:
                  _this.identifier +
                  "/teacherHomeorkAttachment/" +
                  "/" +
                  _this.publishHomework.homeworkTitle +
                  "/" +
                  _this.uploadFile.name,
                StorageClass: "STANDARD",
                Body: _this.uploadFile, // 上传文件对象
                // 进度回调函数
                onProgress: function(progressData) {
                  console.log(progressData.percent);
                  // 更新显示进度条
                  _this.progress = progressData.percent * 100;

                  // progressData.total 整个文件的大小
                  // progressData.loaded 已上传文件内容大小， progressData.speed 上传文件速度， progressData.percent 上传文件百分百
                  // console.log(progressData.total);
                },
              },
              function(err, data) {
                // 这里是打印文件的保存路径
                // console.log(data);

                if (err) {
                  _this.$message.error("作业发布失败");
                } else {
                  // 提示上传成功

                  // 向后端发请求
                  let url = "https://";
                  // 记录信息, 参见接口
                  var address = data.Location;
                  _this.publishHomework.attachmentList[0].link = url + address;
                  _this.submitHomework();

                  _this.havePublished = true;
                  _this.$router.go(0);
                }
              }
            );
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消发布",
          });
        });
    },

    // 身份认证
    getCOS() {
      var cos = new COS({
        AppId: "1304114494",
        SecretId: "AKIDwhU5nHLegU7C5rloQmslkVZOyRgrElU4",
        SecretKey: "d5SdcLMI7IKHzUxDEIAbstnTfIvsa3HJ",
      });
      return cos;
    },

    // 跳转到studentStatistics页面
    studentStatistics() {
      this.$router.push({ name: "studentStatistics" });
    },
  },
  mounted() {
    this.loadHomeworkList();
    this.identifier = this.$store.state.identifier;
  },
};
</script>

<style lang="less" scoped>
// 作业表格
.homeTable {
  width: 100% !important;
  height: 100% !important;
}

// 表格里面的按钮
.tableBtn {
  font-size: 13px;
  color: #797979;
}

// 弹窗“发布课程作业”
.publishTable {
  height: 500px !important;
}

/deep/ .el-dialog__title {
  font-size: 23px;
  color: rgb(51, 55, 68);
}

/deep/ .el-dialog--center .el-dialog__body {
  padding: 25px 25px 0px;
}

/deep/ .el-input {
  width: 260px;
}

/deep/ .el-input__inner {
  border-radius: 0;
  height: 30px;
  border: 1px solid rgb(153, 153, 153);
  font-size: 13px;
}

/deep/ .el-form-item__label {
  color: #333333;
  font-size: 14px;
  text-align: left;
}

/deep/ .el-textarea__inner {
  width: 400px;
  height: 200px;
  border-radius: 0;
  border: 1px solid rgb(153, 153, 153);
}

// 分割线样式
.el-divider--horizontal {
  background-color: rgb(153, 153, 153);
}

// 文件说明
.fileExplain {
  font-size: 12px;
}

//
.publishBtn {
  margin: auto;
  background-color: #5988b3;
  color: #f2f2f2;
}
</style>
